package com.demo.config.mq.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.demo.config.BlackUserProperties;
import com.demo.config.mq.handler.TgBotOneMqConsts;
import com.demo.config.mq.handler.dto.TgMessageDto;
import com.demo.service.CustomTestBot;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;

/**
 * @Description:
 */
@Slf4j
@Service
public class TgBotOneService {

  @Autowired
  private CustomTestBot customTestBot;
  @Autowired
  private RabbitTemplate rabbitTemplate;
  @Autowired
  private BlackUserProperties blackUserProperties;

  public void handler(TgMessageDto dto) {
    Date date = dto.getDate();
    log.info("message 接收时间：{}", date);
    Message message = dto.getMessage();
    Long id = message.getFrom().getId();
    List<String> noReplyId = blackUserProperties.getNoReplyId();
    if(CollUtil.isNotEmpty(noReplyId) && noReplyId.contains(id.toString())){
      log.info("用户永久黑名单, 消息不做处理");
      return;
    }
    SendMessage botPushMsg = dto.getBotPushMsg();
    if(botPushMsg != null){
      log.info("群组信息已存在,不查询接口,直接推送");
      String s = sendBotMsg(botPushMsg);
      if(StrUtil.isNotBlank(s)){
          sendToMq(dto);
      }else{
        log.info("消息回复结束。。。。");
      }
      return;
    }

    SendMessage sendMessage = new SendMessage();
    sendMessage.setChatId(message.getChatId().toString());
    Boolean flag = Boolean.TRUE;
    String orderNo = null;
    if (StringUtils.hasText(message.getText())) {
        orderNo = message.getText();
    } else if (message.getPhoto() != null) {
      orderNo = message.getCaption();
    } else {
      flag = Boolean.FALSE;
    }
    if (!flag) {
      log.info("未匹配到规则,消息结束");
      return;
    }
    List<String> userId = blackUserProperties.getUserId();
    Boolean containFlag = userId.contains(id.toString());

    String specialWord = blackUserProperties.getSpecialWord();
    Boolean specialFlag  =  orderNo.startsWith(specialWord);

    //用户在黑名单 但是没有已特殊消息开头
    if(containFlag){
      //已特殊消息开头
      if(specialFlag){
        orderNo = orderNo.replace(specialWord, "");
      }else{
        log.info("用户id在黑名单里面且订单号没有以标准查询开头,消息不做处理,丢弃,消费结束");
        return;
      }
    }else{
      if(specialFlag){
        log.info("用户id不在黑名单里面但是以标准查询开头,消息不做处理,丢弃,消费结束");
        return;
      }
    }
    //这里判断 orderNo 也就是文本信息是否符合标准？？？？ 不符合丢弃

    //符合则处理

    //调用api 接收 查询结果， 然后组装报文 发送到 群组中
    sendMessage.setText(orderNo);

    String s = sendBotMsg(sendMessage);
    log.info("发送tg群组结果：{}", s);
    if(StrUtil.isNotBlank(s)){
      log.info("发送tg群组失败,重新推送回mq", s);
      dto.setBotPushMsg(sendMessage);
      sendToMq(dto);
    }else{
      log.info("发送tg群组成功,消费结束");
    }
  }

  private void sendToMq(TgMessageDto dto) {
    String timeout = dto.getTimeout();
    timeout = TgBotOneMqConsts.BOT_ONE_DELAY_TIME_MAP.get(timeout);
    if(StrUtil.isNotBlank(timeout)){
      final String timeOutStr = timeout;
      dto.setTimeout(timeOutStr);
      //发送到延迟队列
      rabbitTemplate.convertAndSend(TgBotOneMqConsts.BOT_ONE_DELAY_MODE_QUEUE,
          TgBotOneMqConsts.BOT_ONE_DELAY_QUEUE, dto, mqmessage -> {
            mqmessage.getMessageProperties().setHeader("x-delay", timeOutStr);
            return mqmessage;
          });
      log.info("消息重新推送mq:{}", JSONUtil.toJsonStr(dto));
    }else{
      log.info("消息消费多次均失败,结束:{}", JSONUtil.toJsonStr(dto));
    }
  }

  private String sendBotMsg(SendMessage message) {
    try{
      customTestBot.execute(message);
      log.info("消息回复成功：{}", JSONUtil.toJsonStr(message));
      return null;
    }catch (Exception e){
      log.error("", e);
      return "异常发送失败";
    }
  }
}
